
package inf3791.calendarsystem.soc;

import inf3791.calendarsystem.shared.Appointment;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 * Displays a countdown until the next appointment.
 * 
 * @author Jonas Weber
 */
public class CountdownField extends JLabel implements Runnable {

    public final static String FORMATSTRING = "You have %02d:%02d till next event";
    public final static String NULLSTRING = "You have plenty of time because there is no next event";
    private Appointment nextappointment;
    private static ScheduledThreadPoolExecutor threadpool = new ScheduledThreadPoolExecutor(1);

    public CountdownField()
    {
        refreshText();
    }
    
    public void setNextAppointment(Appointment app) {
        this.nextappointment = app;

        threadpool.remove(this);

        if (app != null) {
            threadpool.scheduleAtFixedRate(this, 0, 30, TimeUnit.SECONDS);
        }
    }

    public Appointment getNextAppointment() {
        return nextappointment;
    }

    String getFormattedString() {

        if (nextappointment == null || nextappointment.getTime().before(new Date())) {
            return NULLSTRING;
        }

        TimeDifference timediff = TimeDifference.fromSubtraction(nextappointment.getTime(), new Date());

        return String.format(FORMATSTRING, timediff.hour, timediff.minute);
    }

    /**
     * refreshes the text shown to match the current time till event, may be
     * called from background thread
     */
    final void refreshText() {

        final String outputString = getFormattedString();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                setText(outputString);
            }
        });
    }

    @Override
    public void run() {
        refreshText();
    }
}
